import { config } from '@/config/';
import { BadRequestException } from '@nestjs/common';
import { conf, form_up, zone, rs, auth } from 'qiniu';
const { Qiniu } = config;

/**
 * ak和sk
 */
const mac = new auth.digest.Mac(Qiniu.accessKey, Qiniu.secretKey);
/**
 * bucket 名称
 */
const options = {
  scope: Qiniu.bucket,
};
const putPolicy = new rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
/**
  * 区域  
       
         机房	Zone对象
         华东	qiniu.zone.Zone_z0
         华北	qiniu.zone.Zone_z1
         华南	qiniu.zone.Zone_z2
         北美	qiniu.zone.Zone_na0
         这个没在配置文件中。
*/
const qiniuConfig = new conf.Config({
  zone: zone.Zone_z2,
});

/**
 *
 * @param buffer :
 * @param fileName 上传后要显示的名称
 * @returns
 */
export const uploadWithQiniu = (buffer, fileName): Promise<string> => {
  const formUploader = new form_up.FormUploader(qiniuConfig);
  const putExtra = new form_up.PutExtra();

  // 打算以后生成一个随机时间的名称

  try {
    if (!buffer) {
      throw new BadRequestException('文件buffer不存在');
    }
    const readableStream = buffer; // 可读的流

    return new Promise((res, rej) => {
      formUploader.put(
        uploadToken,
        fileName,
        readableStream,
        putExtra,
        function (respErr, respBody, respInfo) {
          if (respErr) {
            // throw new BadRequestException(respErr.message);
            rej(respErr.message);
          }
          if (respInfo.statusCode == 200) {
            // console.log('up', respInfo);
            res(Qiniu.url + respBody.key);
          } else {
            res(respInfo);
          }
        },
      );
    });
  } catch (error) {
    console.log(error);
    throw new BadRequestException(error.message);
  }
};

/**
 *
 * @param fileName  : 需要是 七牛云上的文件名
 */
export const deleteWithQinniu = (fileURL): Promise<string> => {
  const fileName = fileURL.split(Qiniu.url)[1];
  let bucketManager = new rs.BucketManager(mac, qiniuConfig);
  return new Promise((res, rej) => {
    bucketManager.delete(
      Qiniu.bucket,
      fileName,
      function (err, respBody, respInfo) {
        if (err) {
          rej(err);
          //throw err;
        }
        if (respInfo.statusCode == 200) {
          res('删除成功');
        } else {
          // console.log('respBody', respBody);
          rej({ message: respBody.error });
        }
      },
    );
  });
};
